package com.ruoyi.web.controller.mes;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.pinyin.PinYinUtils;
import com.ruoyi.common.utils.uuid.UUID;
import com.ruoyi.web.domain.MesCuttingGroup;
import com.ruoyi.web.domain.mes.*;
import com.ruoyi.web.mapper.MesConfigMapper;
import com.ruoyi.web.service.*;
import com.ruoyi.web.mapper.MesCuttingOutboundMapper;
import com.ruoyi.web.service.Impl.MesPaperService;
import com.ruoyi.web.vo.MesCuttingOutbound;
import com.ruoyi.web.vo.MesCuttingOutboundDetail;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

@Api("纸张出库")
@RestController
@RequestMapping("/MesCuttingOutbound")
public class MesCuttingOutboundController extends BaseController {

    @Resource
    private MesCuttingOutboundService mesCuttingOutboundService;
    @Resource
    private MesCuttingOutboundDetailService mesCuttingOutboundDetailService;
    @Resource
    private MesConfigMapper configMapper;

    @Resource
    private MesCuttingOutboundMapper mesCuttingOutboundMapper;

    @Resource
    private MesCuttingGroupService mesCuttingGroupService;


    @Resource
    private MesPaperService mesPaperService;

    //查询list
    @ApiOperation("查询基本信息列表")
    @GetMapping(value = "/list")  //修改成@PostMapping
    public TableDataInfo list(MesCuttingOutbound mesCuttingOutbound) {
        startPage();
        String date="";
        if (mesCuttingOutbound.getOutboundDate()!=null) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
             date = sdf.format(mesCuttingOutbound.getOutboundDate());
        }
        List<MesCuttingOutbound> data = mesCuttingOutboundService
                .list(new QueryWrapper<MesCuttingOutbound>()
                        .lambda()
                        .like(StringUtils.isNotEmpty(mesCuttingOutbound.getOutboundCode()), MesCuttingOutbound::getOutboundCode, mesCuttingOutbound.getOutboundCode())
                        .like(StringUtils.isNotEmpty(mesCuttingOutbound.getMachineName()),MesCuttingOutbound::getMachineName,mesCuttingOutbound.getMachineName())
                        .like(StringUtils.isNotEmpty(date),MesCuttingOutbound::getOutboundDate,date)
                        .orderByDesc(MesCuttingOutbound::getOutboundDate)
                );
        TableDataInfo list = getDataTable(data);
        return list;
    }


    @ApiOperation("纸张出库明细查询")
    @GetMapping("/Detail")
    public TableDataInfo Detail(MesCuttingOutboundDetail mesCut)
    {
        startPage();
        List<MesCuttingOutboundDetail> Outboundlist= mesCuttingOutboundMapper.getCuttingOutboundDetailList(mesCut);
        TableDataInfo list = getDataTable(Outboundlist);
        return list;
    }


    //根据id查询详情
    @ApiOperation("根据id查询详情")
    @GetMapping(value = "/{id}")
    public AjaxResult getById(@PathVariable("id") String id) {
        MesCuttingOutbound mesCuttingOutbound= mesCuttingOutboundService.getById(id);
        List<MesCuttingOutboundDetail> list= mesCuttingOutboundMapper.getCuttingOutboundDetail(id);

//        List<MesCuttingOutboundDetail> mesPrintTechnologyDetailList=mesCuttingOutboundDetailService
//                .list(new QueryWrapper<MesCuttingOutboundDetail>().lambda()
//                                .eq(MesCuttingOutboundDetail::getOutboundId,id));
        mesCuttingOutbound.setMesCuttingOutboundDetails(list);
        return AjaxResult.success("查询成功", mesCuttingOutbound);
    }

    @ApiOperation("根据机台Id查询详情机台出库库存")
    @GetMapping(value = "/getMachineOutboundInfo")
    public TableDataInfo getMachineOutboundInfo(MesCuttingOutboundDetail mesCut) {
        //String  machineId=mesCut.getMachineId();
        startPage();
        List<MesCuttingOutboundDetail> Outboundlist= mesCuttingOutboundMapper.getOutboundInfoByMachineId(mesCut);
        TableDataInfo list = getDataTable(Outboundlist);
        return list;
    }


    //新增或编辑
    @ApiOperation("新增或编辑")
    @PostMapping(value = "/add")
    @Transactional
    public AjaxResult add(@RequestBody MesCuttingOutbound mesCuttingOutbound) {
        if (mesCuttingOutbound.getId()==null) {
            mesCuttingOutbound.setId(UUID.randomUUID().toString().replace("-", ""));

            Map<String, Object> map = new HashMap<>();
            map.put("columnName", "outbound_code");
            map.put("tableName", "mes_cutting_outbound");
            int maxNum = configMapper.getMaxId(map);
            String code = PinYinUtils.getCodeNormal(maxNum, "ZZCQLYD");
            mesCuttingOutbound.setOutboundCode(code);
        }
        mesCuttingOutboundService.saveOrUpdate(mesCuttingOutbound);

        for (MesCuttingOutboundDetail mesCuttingOutboundDetail : mesCuttingOutbound.getMesCuttingOutboundDetails()) {
            if (mesCuttingOutboundDetail.getId()==null) {
                mesCuttingOutboundDetail.setId(UUID.randomUUID().toString().replace("-", ""));
            }
            mesCuttingOutboundDetail.setOutboundId(mesCuttingOutbound.getId());
        }

        if (mesCuttingOutbound.getMesCuttingOutboundDetails() != null && mesCuttingOutbound.getMesCuttingOutboundDetails().size() != 0) {
            mesCuttingOutboundDetailService.remove(new QueryWrapper<MesCuttingOutboundDetail>()
                    .lambda().eq(MesCuttingOutboundDetail::getOutboundId, mesCuttingOutbound.getId()));
            mesCuttingOutboundDetailService.saveBatch(mesCuttingOutbound.getMesCuttingOutboundDetails());
        }
        return AjaxResult.success("操作成功", mesCuttingOutbound.getId());
    }
//更改状态(提交)
    @ApiOperation("更改状态(提交)")
    @PostMapping(value = "/updateStatus")
    @Transactional
    public AjaxResult updateStatus(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        String status = params.get("status");

        if (Objects.equals(status, "2")) {//提交
            //领用主表
            MesCuttingOutbound Info = mesCuttingOutboundService.getById(id);
            //领用详情
            List<MesCuttingOutboundDetail> list = mesCuttingOutboundDetailService.list(new QueryWrapper<MesCuttingOutboundDetail>()
                    .lambda().eq(MesCuttingOutboundDetail::getOutboundId, id));
            if (list != null && list.size() != 0) {

                for (MesCuttingOutboundDetail Detail : list) {
                    MesPaper paper = mesPaperService.selectMesPaperById(Detail.getPaperId());//纸张
                        double total = Detail.getOutboundNumber();
                        if (paper.getQuantity() == null) {
                            throw new ServiceException(paper.getName() + "纸张没有库存！");
                        }
                        int result = paper.getQuantity().compareTo(BigDecimal.valueOf(total));
                        if (result < 0) {
                            throw new ServiceException("出库数量大于纸张库存数量！");
                    }
                }

                for (MesCuttingOutboundDetail Detail : list) {
//                    updateQuantity(Info.getMachineId(), Detail.getPaperId(), Detail.getOutboundNumber());
                    updateCutting(Detail.getPaperId(), Detail.getOutboundNumber());//更改裁切组
                }
            }
        }
    mesCuttingOutboundService.update(new UpdateWrapper<MesCuttingOutbound>().lambda().set(MesCuttingOutbound::getStatus, status).eq(MesCuttingOutbound::getId, id));
        return AjaxResult.success("更新成功");
    }


    private void updateCutting(Long paperid, Double number) {
        List<MesCuttingGroup> mesCuttingGroups= mesCuttingGroupService.list( new QueryWrapper<MesCuttingGroup>().lambda()
                .eq(MesCuttingGroup::getPaperId,paperid));

        if(number==null){
            number=(double) 0;
        }
        if (mesCuttingGroups!=null&&mesCuttingGroups.size()>0){ //修改裁切组库存
            mesCuttingGroupService.update( new UpdateWrapper<MesCuttingGroup>().lambda()
                    .setSql("white_num = white_num + " + number)
                    .eq(MesCuttingGroup::getPaperId,paperid));
        }else{
            //加裁切组数据
            MesCuttingGroup mesCuttingGroup=new MesCuttingGroup();
            mesCuttingGroup.setPaperId(Math.toIntExact(paperid));
            mesCuttingGroup.setWhiteNum(number);
            mesCuttingGroup.setCuttingNum((double) 0);
            mesCuttingGroupService.save(mesCuttingGroup);
        }

        MesPaper paper=new MesPaper();
        paper.setId(paperid);
        paper.setQuantity(BigDecimal.valueOf(number));
        paper.setQuantitymark(2);
        mesPaperService.updateMesPaperQuantity(paper);//减纸库库存
    }


    private void updateQuantity(String machineid, Long paperid, Double number) {
        MesMachinePaper machinepaper = new MesMachinePaper();
        machinepaper.setMachineid(machineid);
        machinepaper.setPaperid(paperid);
        machinepaper.setNumber(BigDecimal.valueOf(number));
        machinepaper.setType((long) 1);
        machinepaper.setMachineType("1");
        int id = mesPaperService.selectMachinePaper(machinepaper);//查询机台纸张
        if (id > 0) {
            mesPaperService.updateMachinePaper(machinepaper);//修改机台纸张
        } else {
            mesPaperService.AddMachinePaper(machinepaper);//添加机台纸张
        }
    }


    //删除
    @ApiOperation("删除")
    @PostMapping(value = "/deleteById")
    public AjaxResult deleteById(@RequestBody Map<String, String> params) {
        String id = params.get("id");
        mesCuttingOutboundService.removeById(id);
        mesCuttingOutboundDetailService.remove(new QueryWrapper<MesCuttingOutboundDetail>().lambda().eq(MesCuttingOutboundDetail::getOutboundId, id));
        return AjaxResult.success("删除成功");
    }


}

